#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#define MSG_FILE "msgserver.c"
#define BUFFER 255
#define PERM S_IRUSR|S_IWUSR
struct msgtype{
	long mtype;
	char buffer[BUFFER+1];
};

int main(int argc, char *argv[])
{
	struct msgtype msg;
	key_t key;
	int msgid;
	if(argc != 2)
	{
		printf("Usage:%s string/n",argv[0]);
		return -1;
	}
	if((key = ftok(MSG_FILE,'a')) == -1)
	{
		printf("Create Key Error:%s\n", strerror(errno));
		return -1;
	}
	if((msgid = msgget(key, PERM)) == -1)
	{
		printf("Create Message Error:%s\n", strerror(errno));
		return -1;
	}
	printf("msqid = %d\n",msgid);
	//set the message
	memset(&msg, 0, sizeof(struct msgtype));
	msg.mtype = 1;
	strncpy(msg.buffer,argv[1],BUFFER);
	//send message	
	msgsnd(msgid, &msg, sizeof(struct msgtype), 0);
	//reset message
	memset(&msg, 0, sizeof(struct msgtype));
	//recv message
	msgrcv(msgid, &msg, sizeof(struct msgtype),2,0);
	printf("Server Received:%s\n", msg.buffer);
	return 0;
}
